package cn.Controller;

import cn.Mapper.UserHomeMapper;
import cn.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UserHomeController {
    @Autowired
    private UserHomeMapper userHome;
    /*@GetMapping("/FindUserByUserName")
    public String FindUserByUserName(Model model,HttpServletRequest request){
        String username1 = (String)request.getSession().getAttribute("username");
        User user1 = (User) request.getSession().getAttribute("USER");

        User user = userHome.FindUserByUserName(username1);
        model.addAttribute("USER",user);
        return "my_home";
    }*/
    @RequestMapping("/upload")
    public String test(@RequestParam("file") MultipartFile multipartFile, User user,HttpServletRequest req) throws IOException {
        if (multipartFile.isEmpty()){
           String username1 = (String)req.getSession().getAttribute("username");
            User user1 = userHome.FindUserByUserName(username1);
            System.out.println(user1);
            user.setImg(user1.getImg());
            userHome.UpdateUserByUserName(user);
        }else {
        String oldname = multipartFile.getOriginalFilename();
        int i = oldname.lastIndexOf(".");
        String substring = oldname.substring(i);
        String string = UUID.randomUUID().toString();
        String newName=string+substring;
        File file=new File("F://WorkSpace/ssm-development-master/src/main/web/product/touxiang");
        if (!file.exists()){
            file.mkdirs();
        }
        String path=file+"/"+newName;
        multipartFile.transferTo(new File(path));
        String imgs="product/touxiang/"+newName;
        user.setImg(imgs);
        userHome.UpdateUserByUserName(user);
        }
        return "redirect:FindUserByUserName";
    }
}
